package com.yin.myproject.arithmetic;

/**
 * 子串p出现在字符串s中的位置
 * 字符串匹配:暴力求解
 *
 * @author Eason
 * @create 2018-04-25 14:45
 **/
public class StringSerach {


    public static void main(String[] args) {
        String origin = "aaabcaaaadeghijikefg";
        String pattern = "aaaa";
        System.out.println(new StringSerach().naiveStringSearch(origin, pattern));
    }

    int naiveStringSearch(String origin, String pattern) {
        int i = 0;
        int j = 0;
        char[] orginChars = origin.toCharArray();
        char[] patternChars = pattern.toCharArray();
        int slength = orginChars.length;
        int plength = patternChars.length;

        while (i < slength && j < plength) {
            if (orginChars[i] == patternChars[j]) {
                i++;
                j++;
            } else {
                i = i - j + 1;
                j = 0;
            }
        }

        if (j == plength) {
            return i - j;
        }

        return -1;
    }
}
